﻿using System;
using System.Collections.Generic;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Electrical;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;

namespace Model
{
	public class HYPlanarConnect : HYCmdEntry
	{
		public HYPlanarConnect(ExternalCommandData commandData) : base(commandData)
		{
		}

		public bool Execute()
		{
			Transaction transaction = null;
			bool result;
			try
			{
				IList<CableTray> list = new List<CableTray>();
				ISelectionFilter selectionFilter = new CableTrayFilter();
				HYCableTrayConnect hycableTrayConnect = new HYCableTrayConnect();
				string text = "平面连接";
				for (;;)
				{
					transaction = new Transaction(this.m_doc, text);
					transaction.Start();
					list.Clear();
					RevitVersionFuncs.ClearSelection(this.m_sel);
					Reference reference = this.m_sel.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element, selectionFilter, "选择第一根桥架");
					list.Add(this.m_doc.GetElement(reference) as CableTray);
					reference = this.m_sel.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element, selectionFilter, "选择第二根桥架");
					list.Add(this.m_doc.GetElement(reference) as CableTray);
					if (!hycableTrayConnect.NewPlanarConnection(list))
					{
						TaskDialog.Show("盈建科提示", "连接失败。");
					}
					else
					{
						this.m_doc.Regenerate();
					}
					transaction.Commit();
				}
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				result = true;
			}
			catch (Exception)
			{
				TaskDialog.Show("盈建科提示", "连接失败，请检查桥架位置是否正确。");
				result = false;
			}
			finally
			{
				if (transaction != null)
				{
					TransactionStatus status = transaction.GetStatus();
					if ((int)status == 1)
					{
						transaction.Commit();
					}
					else if ((int)status == 5)
					{
						transaction.RollBack();
					}
				}
			}
			return result;
		}
	}
}
